package com.visionblue.business.ship.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import com.baidu.location.BDLocation
import com.visionblue.business.ship.model.bean.request.GpsLocationRequest
import com.visionblue.business.ship.model.repository.DeviceInfoRepository
import com.visionblue.business.ship.model.repository.RemoteRepository
import com.visionblue.business.ship.util.MLog
import com.visionblue.business.ship.util.location.LocationCallBack
import com.visionblue.business.ship.util.location.MapLocationHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.koin.android.ext.android.get

/**
 * @author: xlh
 * @date: 2020-06-08 8:43 AM
 * @desc:
 */
class HeartbeatService() : Service(), CoroutineScope by MainScope() {

    private val mapLocationHelper = MapLocationHelper(this)
    private val deviceInfoRepository: DeviceInfoRepository = get()

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        mapLocationHelper.setLocationCallBack(object : LocationCallBack {
            override fun onCallLocationSuc(location: BDLocation?) {
                if (deviceInfoRepository.sn.isEmpty()) {
                    return
                }
                launch {
                    val gpsLocationRequest = GpsLocationRequest(
                        location?.latitude.toString(),
                        location?.longitude.toString()
                    )

                    deviceInfoRepository.latitude = location?.latitude.toString()
                    deviceInfoRepository.longitude = location?.longitude.toString()

                    try {
                        RemoteRepository.postGpsLocation(gpsLocationRequest)
                    } catch (e: Exception) {
                        MLog.e(e.message.toString())
                    }
                }
            }

            override fun onErr() {

            }
        })
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mapLocationHelper.startMapLocation()
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
    }

    companion object {
        fun start(context: Context) {
            Intent(context, HeartbeatService::class.java)
                .run {
                    context.startService(this)
                }
        }
    }
}